package org.jeecg.modules.health_records.files_upload;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUploadUtil {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    /**
     * 上传图片文件
     * @param file 上传的文件
     * @param uploadPath 上传根目录
     * @param allowedExtensions 允许的扩展名(逗号分隔)
     * @return 返回相对路径
     * @throws IOException
     * @throws IllegalArgumentException 当文件类型不符合要求时抛出
     */
    public static String uploadImage(MultipartFile file, String uploadPath, String allowedExtensions)
            throws IOException, IllegalArgumentException {

        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        // 获取原始文件名和扩展名
        String originalFilename = file.getOriginalFilename();
        String fileExt = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();

        // 检查文件类型
        if (!isAllowedExtension(fileExt, allowedExtensions)) {
            throw new IllegalArgumentException("只允许上传以下类型的图片: " + allowedExtensions);
        }

        // 按日期生成目录
        String dateDir = sdf.format(new Date());
        String savePath = uploadPath + File.separator + dateDir + File.separator;

        // 创建目录
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }

        // 生成新的文件名（防止重名）
        String newFileName = UUID.randomUUID().toString().replace("-", "") + fileExt;
        String fullPath = savePath + newFileName;

        // 保存文件
        file.transferTo(new File(fullPath));

        return dateDir + "/" + newFileName;
    }

    /**
     * 检查文件扩展名是否允许
     */
    private static boolean isAllowedExtension(String fileExt, String allowedExtensions) {
        if (fileExt == null || fileExt.isEmpty()) {
            return false;
        }

        String ext = fileExt.toLowerCase().replace(".", "");
        String[] allowedExts = allowedExtensions.toLowerCase().split(",");

        for (String allowedExt : allowedExts) {
            if (allowedExt.trim().equals(ext)) {
                return true;
            }
        }
        return false;
    }
}